﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using PollSystemDAL;

namespace PollSystemService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class PollSystemService : IPollSystemService
    {
        public QuestionDTO[] GetQuestions()
        {
            var questions = PollSystemDAO.GetQuestions();
            QuestionDTO[] questionDTOs = new QuestionDTO[questions.Length];

            for(int i=0; i< questions.Length; i++)
            {                
                questionDTOs[i] = new QuestionDTO();
                questionDTOs[i].Constructor(questions[i]);
            }

            return questionDTOs;
        }

        public AnswerDTO[] GetAnswers()
        {
            var answers = PollSystemDAO.GetAnswers();
            AnswerDTO[] answersDTOs = new AnswerDTO[answers.Length];

            for (int i = 0; i < answers.Length; i++)
            {
                answersDTOs[i] = new AnswerDTO();
                answersDTOs[i].Constructor(answers[i]);
            }

            return answersDTOs;
        }

        public AnswerDTO[] GetAnswersByQuestionId(string questionId)
        {
            int questionIdInt;

            if (!Int32.TryParse(questionId, out questionIdInt))
            {
                throw new FormatException("questionId was not a valid int.");
            }

            var answers = PollSystemDAO.GetAnswersByQuestionId(questionIdInt);
            AnswerDTO[] answersDTOs = new AnswerDTO[answers.Length];

            for (int i = 0; i < answers.Length; i++)
            {
                answersDTOs[i] = new AnswerDTO();
                answersDTOs[i].Constructor(answers[i]);
            }

            return answersDTOs;
        }

        public void VoteForAnswer(string answerId)
        {
            int answerIdInt;

            if (!Int32.TryParse(answerId, out answerIdInt))
            {
                throw new FormatException("answerId was not a valid int.");
            }

            PollSystemDAO.VoteForAnswer(answerIdInt);
        }

        public AnswerDTO[] VoteForAnswerAndGetVotesCount(string answerId)
        {
            int answerIdInt;

            if (!Int32.TryParse(answerId, out answerIdInt))
            {
                throw new FormatException("answerId was not a valid int.");
            }

            PollSystemDAO.VoteForAnswer(answerIdInt);

            int questionId = PollSystemDAO.GetQuestionIdByAnswerId(answerIdInt);

            return GetAnswersByQuestionId(questionId.ToString());
        }
    }
}
